# 工具函数模块
# 判断值为空
def empty(variable):
	if not variable:
		return True
	return False

# 加载json数据
def json_decode(json_str):
    import json
    str = json.loads(json_str)
    return str


def json_encode(str):
    import json
    json_str = json.dumps(str)
    return json_str

def md5(str):
    import hashlib
    m = hashlib.md5()
    m.update(str.encode("utf-8"))
    return m.hexdigest()

# 获取当前php秒级时间戳
def time():
    import time
    t = time.time()
    return int(t)
    
# 判断当前是否数字
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

# 设置跨域请求Credentials允许回应头
def set_response(response):
    response["Access-Control-Allow-Origin"] = "http://localhost:8080"
    response["Access-Control-Allow-Credentials"] = "true"
    response["Access-Control-Allow-Methods"] = "GET,POST,OPTIONS"
    response["Access-Control-Allow-Headers"] = "Origin,Content-Type,Cookie,Accept,Token"
    return response

# 判断代理ip是否可用
# 参数为ip:端口 , flag为true时代表为https , flase 为http, port为空默认80
def proxy_test(proxies_ip, flag, port = 80):
    import requests
    # 判断抓取到的是否空代理ip 或者本机对外ip
    if empty(proxies_ip) or (proxies_ip == '183.6.90.132'):
        print("代理IP:'"+ proxies_ip + "'获取错误！__________")
        return False


    if flag:
        icanhazip_proxies =  {
            'https': "https://" + proxies_ip + ':' + str(port),
        }
    else:
        icanhazip_proxies =  {
            'http': "http://" + proxies_ip + ':' + str(port),
        }
    
    try:
        # 避免验证网站连接失败
        requests.adapters.DEFAULT_RETRIES = 5
        s = requests.session()
        s.keep_alive = False # 关闭多余连接

        # 验证代理ip可用性
        res = s.get(url="http://icanhazip.com/", timeout=8, proxies=icanhazip_proxies)

        proxyIP = res.text
        
        if(proxyIP.strip() == proxies_ip.strip()):
            print("代理IP:'" + proxies_ip + "'有效！__________")
            return True
        else:
            print("代理IP:'" + proxies_ip + "'无效,拒绝代理！__________")
            return False
    except Exception as e :
        # 代理ip无法连接/拒绝
        print("代理IP"+ proxies_ip +"无效,连接错误！__________")
        return False